<template>
  <div class="app-container">
     <div class="filter-container">
      <!-- <el-select
        v-model="state"
        clearable
        placeholder="筛选"
        style="width: 200px;"
        class="filter-item"
      >
        <el-option :value="[0]" label="待处理">待处理</el-option>
        <el-option :value="[1,2]" label="已处理">已处理</el-option>
        <el-option :value="[]" label="全部">全部</el-option>
      </el-select> -->
      <el-select
        v-model="orderReqDto.powerCardState"
        clearable
        placeholder="是否会员"
        style="width: 200px;"
        class="filter-item"
      >
        <el-option :value="0" label="非会员">非会员</el-option>
        <el-option :value="1" label="会员">会员</el-option>
        <el-option :value="2" label="全部">全部</el-option>
      </el-select>
       <el-input v-model="orderReqDto.phone" placeholder="手机号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="编号" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="内容" align="left" mini-width="150">
        <template slot-scope="{row}">
          <span>{{ row.content }}</span>
        </template>
      </el-table-column>
       <!-- <el-table-column label="图片" align="center" width="150">
        <template slot-scope="{row}">
            <el-image style="width: 100px; height: 100px" :src="row.images"  :preview-src-list="srcList">
              <div slot="error" class="image-slot" style="padding-top:45px">未上传图片</div>
            </el-image>
        </template>
      </el-table-column> -->
      <el-table-column label="是否已读" align="center" width="100">
        <template slot-scope="{row}">
          <el-tag v-if="row.dealState ===0" type="primary">未读</el-tag>
          <el-tag v-if="row.dealState ===1||row.dealState ===2||row.dealState ===3" type="success">已读</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="150" align="center">
        <template slot-scope="{row}">
          {{ row.phone }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="160" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime  }}</span>
        </template>
      </el-table-column>
       <!-- <el-table-column label="回复时间" width="160" align="center">
        <template slot-scope="{row}">
          <span>{{ row.dealTime  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="回复内容" width="160" align="center">
        <template slot-scope="{row}">
          <span>{{ row.dealContent }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" width="320" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="info" size="mini" @click="check(row)"  v-show="row.dealState ===0">
            确认已读
          </el-button><el-button type="info" size="mini" @click="check(row)"  v-show="row.dealState ===1||row.dealState ===2||row.dealState ===3" disabled>
            确认已读
          </el-button>
          <el-button type="primary" size="mini" @click="pull(row)">
            回复留言
          </el-button>
          <!-- <el-button type="warning" size="mini" @click="handlereply(row)">
            回复留言
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="orderReqDto.current"
      :limit.sync="orderReqDto.size"
      @pagination="getCustomerserivces"
    />
   <!-- 富文本图片放大 -->    
  <div class="imgDolg" v-show="imgPreview.show" @click.stop="imgPreview.show = false">      
    <i class="el-icon-close" id="imgDolgClose" @click.stop="imgPreview.show = false"></i>      
    <img @click.stop="imgPreview.show = true" :src="imgPreview.img" />    
  </div>

   <el-dialog
      title="客服记录"
      :visible.sync="dialogFormVisible"
      width="450px"
      height="300px"
    >
      <div class="test1" id="test1" style="height:450px;overflow-y:scroll;overflow-x:none;">
        <div v-for="item in msgs" :key="item.id" class="traces">
           <div style="text-align:center;margin:10px">{{item.createTime}}</div>
          <div :class="item.role == '易薪客服' ? 'right' : 'left'">
            <img
              :src="
                item.role == '易薪客服'
                  ? 'https://yix-static.oss-cn-hangzhou.aliyuncs.com/yixinh5/waiter.png'
                  : 'https://yix-static.oss-cn-hangzhou.aliyuncs.com/yixinh5/user.png'
              "
              :class="item.role == '易薪客服' ? 'rightimg' : 'leftimg'"
            />
            <div
              :class="item.role == '易薪客服' ? 'rightcontent' : 'leftcontent'"
              v-html="item.content"
              @click="showImg($event)"
            />
          </div>
        </div>
      </div>
      <el-upload
        class="upload-demo"
        :action="action"
        :on-exceed="exceedFile"
        :on-error="handleError"
        :on-success="handleSuccess"
        :limit="1"
        :file-list="fileList"
      >
        <el-button size="small" type="primary" style="margin-left:8px;margin-bottom:5px">点击上传图片</el-button>
      </el-upload>
      <div>
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="dto"
          style="width: 400px;margin:auto"
        >
          <el-form-item>
            <el-input
              v-model="dto.content"
              type="textarea"
              maxlength="200"
              show-word-limit
              :rows="4"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel()">
            取消
          </el-button>
          <el-button type="primary" @click="reply()">
            回复
          </el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="客服回复" :visible.sync="editdialog">
      <el-form ref="dataForm" :rules="rules" :model="dto" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="回复内容">
          <textarea v-model="dto.content" type="text" style="width:400px;height:200px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">
          取消
        </el-button>
        <el-button type="primary" @click="reply()">
          回复
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { newList, related, haveRead, newReply } from '@/api/service'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'Service',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      state:[],
      action: process.env.VUE_APP_BASE_API.split('/')[0] + '//' + process.env.VUE_APP_BASE_API.split('/')[2] + '/api/foundation/api/file/upload',
      srcList:[],
      msgs: [],
      tableData: [],
      total: 0,
      tableKey: 0,
      orderReqDto: {
        size: 10,
        current: 1,
        dealState:[],
        powerCardState:2,
        phone:""
      },
      countOrder: {},
      dialogFormVisible: false,
      editdialog: false,
      dto: {
        requestNo: '',
        content: '',
        images:""
      },
      dialogStatus: '',
      textMap: {
        update: '订单流水'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        username: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      listLoading: false,
      orderNoForDetail: '',
      optionsCopy: [],
      options: [],
      value: '',
      imgPreview:{  img:"",  show:false},
      fileList: [],
    }
  },
  created() {
    this.getCustomerserivces(this.orderReqDto)
  },
  updated () {
    this.$nextTick(()=>{
      var container= document.getElementById("test1")
      container.scrollTop=container.scrollHeight
    })
  },
  methods: {
    handleSuccess(res, file, fileList) {
      this.dto.images = res.data // 服务器返回的文件地址
      this.fileList[0] = file
      this.$message({
        message: '文件上传成功',
        type: 'success'
      })
    },
    handleError(err, file, fileList) {
      this.$message.error(err.msg)
    },
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: '警告',
        message: `只能选择1个文件，当前共选择了 ${files.length + fileList.length} 个`
      })
    },
    showImg(e){
      // 点击v-html节点判断当前点击是否是img,如果是获取img的url 
      if (e.target.tagName == 'IMG') {      
        this.imgPreview.img = e.target.src       
        this.imgPreview.show = true
      }  
    },
    dataFilter(val) {
      this.value = val
      if (val) { // val存在
        this.options = this.optionsCopy.filter((item) => {
          if (!!~item.channel_name.indexOf(val) || !!~item.channel_name.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          }
        })
      } else { // val为空时，还原数组
        this.options = this.optionsCopy
      }
    },
    // 获取订单列表
    async getCustomerserivces(orderReqDto) {
      const res = await newList(this.orderReqDto)
      if(res.data.data.records){
          res.data.data.records.forEach((item)=>{
              this.srcList.push(item.images)
          })
      }
      if (res.data.data.records === null) {
        this.tableData = null
      } else {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }
    },
    // 确认已读
    async check(row) {
      const res = await haveRead({ requestNo: row.requestNo })
      if (res.data.code === 200) {
        this.getCustomerserivces()
        this.$notify({
          title: '确认已读！',
          message: '确认成功',
          type: 'success',
          duration: 2000
        })
      } else {
        this.$notify({
          title: '确认已读！',
          message: '确认失败',
          type: 'fail',
          duration: 2000
        })
      }
    },
    async pull(row) {
       this.fileList=[]
      this.dto.content = ""
      this.dto.images=""
      this.dto.requestNo = row.requestNo;
      this.requestNo=row.requestNo
      const res = await related({ requestNo:this.requestNo });
      this.msgs = res.data.data;
      this.msgs.forEach((item) => {
        if (item.images) {
          let imgageArr = item.images.split(",");
          let imageStr = "";
          imgageArr.forEach((ited) => {
            imageStr += `<img style="width:100px;height:100px" src=${ited}>`;
          });
          item.content = `${item.content}<div>${imageStr}</div>`;
        }
      });
      this.dialogFormVisible = true;
    },
    handleFilter() {
      this.orderReqDto.current = 1
      this.orderReqDto.all = false
      this.orderReqDto.dealState=this.state
      if(this.state){
        this.orderReqDto.dealState=this.state
      }else{
        this.orderReqDto.dealState=[]
      }
      this.getCustomerserivces(this.orderReqDto)
    },
    cancel() {
      this.dialogFormVisible = false
    },
    handlereply(row) {
      this.dto.requestNo = row.requestNo
      this.dto.content = ''
      this.editdialog = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 回复
    async reply() {
      const res = await newReply(this.dto)
      if (res.data.code === 200) {
        this.$notify({
          title: '客服回复！',
          message: res.data.msg,
          type: 'success',
          duration: 2000
        })
        this.getCustomerserivces()
      } else {
        this.$notify({
          title: '客服回复！',
          message: res.data.msg,
          type: 'fail',
          duration: 2000
        })
      }
      this.fileList=[]
      this.dto.content = ""
      this.dto.images=""
      const res1 =await related({ requestNo:this.requestNo });
      this.msgs = res1.data.data;
      this.msgs.forEach((item) => {
        if (item.images) {
          let imgageArr = item.images.split(",");
          let imageStr = "";
          imgageArr.forEach((ited) => {
            imageStr += `<img style="width:100px;height:100px" src=${ited}>`;
          });
          item.content = `${item.content}<div>${imageStr}</div>`;
        }
      });
    }
  }
}
</script>
<style scoped>
  /* 图片放大框样式   */
  .imgDolg {  width: 100vw;  height: 100vh;  position: fixed;  z-index: 9999;  background-color: rgba(0, 0,0, 0.6);  top: 0;  left: 0;  display: flex;  align-items: center;  
    justify-content: center; 
  }
  #imgDolgClose {    position: fixed;    top: 35px;    cursor: pointer;    right: 7%;    font-size: 50px;    color: white;  }  
  .imgDolg img{    width: 35%;  }
</style>
<style scoped>
.traces{
  overflow:hidden;
}
.left{
  overflow:hidden;
  margin-left: 15px;
  margin-top: 10px;
  width: 100%;
}
.leftcontent{
  word-wrap:break-word;
  padding-left: 10px;
  padding-right: 10px;
  margin-left: 10px;
  border-radius: 5px;
  color: #666666;
  background-color: #EBEBEB;
  width: 235px;
  float: left;
  text-align:left;
  line-height: 40px;
}
.divimg{
  width: 28px;
}
.leftimg{
  display: block;
  float: left;
  width: 38px;
  border-radius: 50%;
}
.rightimg{
  margin-right: 15px;
  display: block;
  float: right;
  width: 38px;
  border-radius: 50%;
}
.right{
  overflow:hidden;
  padding-right: 10px;
  margin-top: 10px;
  width: 100%;
}
.rightcontent{
  word-wrap:break-word;
  padding-left: 10px;
  padding-right: 10px;
  margin-right: 10px;
  border-radius: 5px;
  background-color: #F6AC02;
  color: white;
  width: 235px;
  float: right;
  text-align:left;
  line-height: 40px;
}
.test1::-webkit-scrollbar {
 width: 0;
}
 .test1::-webkit-scrollbar-track {
 background-color:white;
 -webkit-border-radius: 2em;
 -moz-border-radius: 2em;
 border-radius:2em;
}
 .test1::-webkit-scrollbar-thumb {
 background-color:white;
 -webkit-border-radius: 2em;
 -moz-border-radius: 2em;
 border-radius:2em;
}
</style>
